<?php
/** 
 * Created by RisingSun. 
 * User: MarkSpace 
 * Date: 20220315
 * Time: 11:05 
 * 账户管理
 */
namespace app\user\controller;

use  Mscore\Core\Controller;
use  app\user\model\Common as CommonModel;
use  app\user\model\Account as AccountModel;
use  app\admin\model\Login as LoginModel;
use  app\user\model\Qrocde as QrocdeModel;
use  Mscore\Core\Lib\ArrayMethod;
use  Mscore\Core\Lang;
use  Mscore\Core\Util\Util;
use  Mscore\Core\Lib\Mailer;


class AccountController extends Controller{
    
    private $model;
    private $login;
    private $error;
    private $success;
    /**
     * 初始化自动连接方法
     * @param array $sysmod 
     * @param array $where 
    */
    public function __construct()  
    {    
        $this->model = new AccountModel;
        $this->login = (new LoginModel)->isAuth();
        if(isset($this->login['code'])&&$this->login['code']==401){
            echo json_encode($this->login);
            Header("Location:".config('server.login_url'));
            exit;
        }
        $this->language = isset($_COOKIE['language'])?$_COOKIE['language']:'default';
        Lang::init($this->language);
        $this->success=Lang::get('Success');
        $this->error=Lang::get('Error');
    }   

    /**
     * 账户列表
     * @param array $list 
     * @param array $where 
     */ 
    public function list(){
        $post = post();
        // print_r($this->login['checkrole']);die;
        if ($post) {
            $page = post('page',1);
            $limit = post('limit',10);
            // print_r(post('roletype'));
            $where = ' a.dels < 1 and a.type < 2';
            if($this->login['info']['ranges']<1){
                $where .= ' and (a.pid = '.$this->login['info']['aid'].' or a.aid='.$this->login['info']['aid'].')';
            }
            if(post('type')){
                $where .= ' and a.grade = "'.post('type').'" ';
            }
            if(post('username')){
                $where .= ' and a.username like "%'.post('username').'%" ';
            }
            if(post('mobile')){
                $where .= ' and a.mobile like "%'.post('mobile').'%" ';
            }
            if(post('realname')){
                $where .= ' and a.realname like "%'.post('realname').'%" ';
            }
            if(post('roletype')){
                $where .= ' and a.roletype = '.post('roletype');
            }
            $datalist = $this->model->list($where,$page,$limit);
            $data = [
                "code" => 200,
                "data" => $datalist['datalist'],
                "count"=> $datalist['total'],
                "msg" => 'ok'
            ];
            $this->echojson($data);
        } else {
            $rolelist = (new CommonModel())->getrole('dels<1 and status>0');
            $type=!empty(get('type'))?get('type'):'';
            $this->assign('type', $type);
            $this->assign('rolelist', $rolelist);
            $this->display('list.html');
        }
    }

    /**
     * 账户列表
     * @param array $list 
     * @param array $where 
     */ 
    public function checklist(){
        $post = post();
        if ($post) {
            $page = post('page',1);
            $limit = post('limit',10);
            $where = ' a.dels < 1 ';
            if($this->login['info']['ranges']<1){
                $where .= ' and a.pid = '.$this->login['info']['aid'];
            }
            if(post('user_name')){
                $where .= ' and a.user_name like "%'.post('user_name').'%"';
            }
            if(post('mobile')){
                $where .= ' and a.mobile like "%'.post('mobile').'%"';
            }
            if(post('nickname')){
                $where .= ' and a.nickname like "%'.post('nickname').'%"';
            }
            $roletype=!empty(post('roletype'))?post('roletype'):3;
            // if(post('roletype')){
                $where .= ' and a.roletype = '.$roletype;
            // }
            $datalist = $this->model->list($where,$page,$limit);
            $data = [
                "code" => 200,
                "data" => $datalist['datalist'],
                "count"=> $datalist['total'],
                "msg" => 'ok'
            ];
            $this->echojson($data);
        } else {
            $rolelist = (new CommonModel())->getrole('dels<1 and status>0');
            $this->assign('rolelist', $rolelist);
            $this->display('checkuser.html');
        }
    }

  /**
     * 个人信息
     * @param array $info 
     * @param array $where 
     */ 
  public function info(){
       $params = post();
       if($params){
            //post请求则保存
            $datainfo = $this->model->infosave($params);
            switch ($datainfo) {
                case true:
                    $this->echoJson($this->success);
                    break;
                    
                default:
                    $this->echoJson($this->error);
                    break;
            }
       }else{
            $user=array();
            $user['aid']=$this->login['info']['aid'];
            unset($this->login['info']['aid']);
            $info =$this->model->info($user);
            $share=(new CommonModel())->getBaseinfo('keyname="share"', 'content')['content'];
            $info['share'] = isset($info['usercode'])?$share['url'].$info['usercode']:'';
            $info['showewm']=false;
            if (file_exists(config('file.path') . $info['ewmurl'])) {
              $info['showewm']=true;
            }
            $info['showshare']=false;
            if (file_exists(config('file.path') . $info['shareurl'])) {
              $info['showshare']=true;
            }
            $this->assign('datainfo', $info);
            $this->display('info.html');
       }
   
  }

  /**
     * 綁定上綫
     * @param array $check 
     * @param array $where 
     */ 
    public function check(){
       $params = post();
       if($params){
           //post请求则保存
           $data = $this->model->checksave($params);
           switch ($data) {
              case true:
                $this->echoJson($this->success);
                break;
                    
              default:
                $this->echoJson($this->error);
                break;
            }  
       }else{
           $rolelist = (new CommonModel())->getrole('dels<1 and status>0 and grade !="superadmin"');
           if(get('id')){
               $info = $this->model->info('aid='.get('id'));
           }
            //定义变量info输出
            $info['aid']=isset($info['aid'])?$info['aid']:'';
            $info['roletype']=isset($roletype)?$roletype:$info['roletype'];
            $info['ranges']=isset($ranges)?$ranges:$info['ranges'];
            $info['grade']=isset($info['grade'])?$info['grade']:$grade;
            $info['pid']=isset($info['pid'])?$info['pid']:$pid;
            $info['subrealname']=isset($info['subrealname'])?$info['subrealname']:'';
            $info['usercode']=isset($info['usercode'])?$info['usercode']:'';
           
            $this->assign('user', $this->login['info']);
            $this->assign('rolelist', $rolelist);
            $this->assign('datainfo', $info);
            $this->display('check.html');
       }
    }

    /**
     * 账户添加
     * @param array $add 
     * @param array $where 
     */ 
    public function add(){
       $params = post();
       if($params){
           //post请求则保存
           $data = $this->model->save($params);
           switch ($data) {
              case true:
                $this->echoJson($this->success);
                break;
                    
              default:
                $this->echoJson($this->error);
                break;
            }  
       }else{
           $rolelist = (new CommonModel())->getrole('dels<1 and status>0');
           
           if(get('id')){
               $info = $this->model->info('aid='.get('id'));
           }
           // 判断是否管理员添加
           if($this->login['info']['grade']=='superadmin'){
               $pid = isset($info['pid'])&&!empty($info['pid'])?$info['pid']:0;
           }else{
               $pid = isset($info['pid'])&&!empty($info['pid'])?$info['pid']:$this->login['info']['aid'];
           }
            $grade=isset($info)?$info['grade']:'member';
            foreach ($rolelist as $key => $value) {
                if($value['grade']==$grade){
                    $roletype=$value['id'];
                    $ranges = $value['ranges'];
                }
            }
            //定义变量info输出
            $info['aid']=isset($info['aid'])?$info['aid']:'';
            $info['username']=isset($info['username'])?$info['username']:'';
            $info['password']=isset($info['password'])&&!empty($info['password'])?'':'000000';
            $info['paypwd']='';
            $info['realname']=isset($info['realname'])?$info['realname']:'';
            $info['mobile']=isset($info['mobile'])?$info['mobile']:'';
            $info['email']=isset($info['email'])?$info['email']:'';
            $info['roletype']=isset($roletype)?$roletype:$info['roletype'];
            $info['ranges']=isset($ranges)?$ranges:$info['ranges'];
            $info['grade']=isset($info['grade'])?$info['grade']:$grade;
            $info['pid']=isset($info['pid'])?$info['pid']:$pid;
            $info['subrealname']=isset($info['subrealname'])?$info['subrealname']:'';
            $info['header_url']=isset($info['header_url'])?$info['header_url']:'';
            $info['status']=isset($info['status'])?$info['status']:0;
            $info['usercode']=isset($info['usercode'])?$info['usercode']:'';
            // $info['credibility']=isset($info['credibility'])?$info['credibility']:420;
            // $info['borrow']=isset($info['borrow'])?$info['borrow']:0;
           
            $this->assign('user', $this->login['info']);
            $this->assign('rolelist', $rolelist);
            $this->assign('datainfo', $info);
            $this->display('add.html');
       }
    }

    /**
     * 完善账户信息
     * @param array $accperfect 
     * @param array $where 
     */ 
    public function accperfect(){
        header('Location:/user/cert/add/?id='.get('id'));
    }

    /**
     * 分享信息
     * @param array $share 
     * @param array $where 
     */ 
    public function share(){
       $params = post();
       if($params){
           //post请求则保存
            $user = $this->model->info(' aid='.$params['aid']); 
            $sc = isset($params['sc'])?$params['sc']:false;
            switch ($sc) {
                case 1:
                  $share=(new CommonModel())->getBaseinfo('keyname="share"', 'content')['content'];
                  $Qrocde = new QrocdeModel();
                  $data['data'] = $share['url'].$user['usercode'];
                  $data['aid'] = $user['aid'];
                  $data['logurl'] =!empty($user['header_url'])&&file_exists(config('file.path') . $user['header_url'])?$user['header_url']:"/static/qrcode/logo.jpg";
                  $data['qrurl'] = "static/upload/qrcode/".$user['aid'].'.png';
                  $data['name'] = $user['aid'];
                  $shareurl = $Qrocde->qrcode($data);
                  $data=['ewmurl' => $shareurl];
                  $datainfo = $this->model->updateback($data,$params['aid']);
                  break;
                case 2:
                    if (empty($user['backurl']) || !file_exists(config('file.path') . $user['backurl'])) {
                       $this->echoJson(['code'=>100,'msg'=>'请添加背景图']);
                       return false;
                    }
                  $Qrocde = new QrocdeModel();
                  $data['qrcode'] = $user['ewmurl'];
                  $data['back'] =$user['backurl'];
                  $data['share'] = "static/upload/qrcode/share" . $user['aid'] . '.png';
                  $shareurl = $Qrocde->sharepic($data);
                  $data=['shareurl' => $shareurl];
                  $datainfo = $this->model->updateback($data,$params['aid']);
                  break;
                default:
                  $data=['backurl' => $params['backurl']];
                  $datainfo = $this->model->updateback($data,$params['aid']);
                  break;
            }
            switch ($datainfo) {
              case true:
                $this->echoJson($this->success);
                break;
                    
              default:
                $this->echoJson($this->error);
                break;
            } 
       }else{
          if(get('id')){
              $user = $this->model->info(' aid='.get('id'));
          }
          $share=(new CommonModel())->getBaseinfo('keyname="share"', 'content')['content'];
          $user['ewmurl']=isset($user['ewmurl'])?$user['ewmurl']:'';
          $user['shareurl']=isset($user['shareurl'])?$user['shareurl']:'';
          $share=(new CommonModel())->getBaseinfo('keyname="share"', 'content')['content'];
          $user['share'] = isset($user['usercode'])?$share['url'].$user['usercode']:'';
          $user['baseurl'] = config('file.baseurl');
          $this->assign('user', $user);
          $this->display('share.html');
       }
    }
    
    /**
     * 人员删除
     * @param array $userdel 
     * @param array $where 
     */  
    public function del(){ 
        $aid = post('id');
        $user=array('aid'=>$aid);
        $datadel = $this->model->del($user);
        switch ($datadel) {
            case true:
                $this->echoJson($this->success);
                break;
                    
            default:
                $this->echoJson($this->error);
                break;
        }  
    }

    /**
     * 下线账户列表
     * @param array $sublist 
     * @param array $where 
     */ 
    public function sublist(){
        $post = post();
        if ($post) {
            $page = post('page',1);
            $limit = post('limit',10);
            $where = ' a.dels < 1 and a.pid ='.post('aid',false);
            if(post('username')){
            $where .= ' and a.username like "%'.post('username').'%"';
            }
            if(post('mobile')){
            $where .= ' and a.mobile like "%'.post('mobile').'%"';
            }
            if(post('realname')){
            $where .= ' and a.realname like "%'.post('realname').'%"';
            }
            $datalist = $this->model->list($where,$page,$limit);
            $data = [
                "code" => 200,
                "data" => $datalist['datalist'],
                "count"=> $datalist['total'],
                "msg" => 'ok'
            ];
            $this->echojson($data);
        } else {
            $this->assign('aid', get('id'));
            $this->display('sublist.html');
        }
    }
    /**
     * 查看密码
     * @param array $showpwd 
     * @param array $where 
     */ 
    public function showpwd(){
        $post = post();
        if ($post) {
            $user = $this->model->info(' aid='.$post['aid'],'showpwd');
            $user=isset($user['showpwd'])&&!empty($user['showpwd'])?json_decode($user['showpwd'],true):['password'=>'','paypwd'=>''];
            $spwd=(new CommonModel())->getBaseinfo('keyname="authweight"', 'content')['content'];
            $spwd['use']=isset($spwd['use'])&&!empty($spwd['use'])?$spwd['use']:2;
            if( $spwd['use'] > 1 ){
                if($spwd['use']==2){
                    $id=(new CommonModel())->getcode($post['code']);
                }
                if($spwd['use']==3){
                    $id=(new CommonModel())->getcode($post['code'], ' and aid='.$post['aid']);
                }
                if(!$id){return $this->echojson($this->error);}
            }
            switch ($spwd['type']) {
                case 1:
                    $user['paypwd']=!empty($user['paypwd'])?Util::phpDecode($user['paypwd']):'1';
                    $this->success['data']=['paypwd'=>$user['paypwd']];
                    return $this->echojson($this->success);
                    break;
                case 2:
                    $user['password']=!empty($user['password'])?Util::phpDecode($user['password']):'1';
                    $this->success['data']=['password'=>$user['password']];
                    return $this->echojson($this->success);
                    break;
                case 3:
                    $user['password']=!empty($user['password'])?Util::phpDecode($user['password']):'1';
                    $user['paypwd']=!empty($user['paypwd'])?Util::phpDecode($user['paypwd']):'1';
                    $this->success['data']=['paypwd'=>$user['paypwd'],'password'=>$user['password']];
                    return $this->echojson($this->success);
                    break;
            }
            return $this->echojson($this->error);
        }else{
            if(empty(get('id'))){
                echo "参数丢失";
                exit;
            }
            $spwd=(new CommonModel())->getBaseinfo('keyname="authweight"', 'content')['content'];
            $spwd['use']=isset($spwd['use'])&&!empty($spwd['use'])?$spwd['use']:2;
            $this->assign('spwd', $spwd);
            $this->assign('aid', get('id'));
            $this->display('showpwd.html');
        }  
    }

    /**
     * 发送邮件
     * @param array $showpwd 
     * @param array $where 
     */ 
    public function sendmail(){
        $params=post();
        if(!empty($params['type'])){
            $spwd=(new CommonModel())->getBaseinfo('keyname="authweight"', 'content')['content'];
            $email=!empty($spwd['email'])?$spwd['email']:config('config.pwdemail');
            if(empty($email)) $this->echoJson(Lang::get('Emailempty'));
            $template=(new CommonModel())->getBaseinfo('keyname="smstemplate"','content')['content'];
            $template=isset($template[$params['type']])&&!empty($template[$params['type']])?$template[$params['type']]:'';
            if(!empty($template)&&preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/',$email)){
                //整理模版
                $template=explode(':',$template);
                $outtime=isset($template[2])?$template[2]:300;
                $code=rand(1000,9999);
                $endtime=time()+$outtime;
                $st=(new CommonModel())->savacode('aid='.$params['aid'].' and email="'.$email.'"',['code'=>$code,'endtime'=>$endtime,'aid'=>$params['aid'],'email'=>$email]);
                if(!$st){
                  return $this->echojson($this->error);
                }
                //整理数据发送
                $subject=isset($template[0])?$template[0]:'测试';
                $content=isset($template[1])?$template[1]:'测试测试';
                $search = '{'.$params['type'].'}';
                $content = str_replace($search, '<b>'.$code.'</b>', $content);
                Mailer::send($email,$subject,$content);
                $this->success['data']=['endtime'=>$endtime];
                return $this->echojson($this->success);
            }else{
                return $this->echojson($this->error);
            }
        }
        return $this->echojson($this->error);
    }

}
